
__doc__ =   """ This module contains the einput function.
            """

from Holders import Holder, ChainHolder, ResidueHolder, AtomHolder
hierarchy = ['H','S','M','C','R','A']

def einput(entities, level, name ='einput'):
    """ input: MultiEntity or other iterable of entites.
        output: Holder of entities of given level.
    """
    # Keep it bug-free
    all = {}
    index = hierarchy.index(level)
    for entity in entities:                     # __iter__ override in Entity
        if index > hierarchy.index(entity.level):       # call for children
            all.update(get_children(entity, level))
        elif  index < hierarchy.index(entity.level):    # call for parents
            all.update(get_parent(entity, level))
        else:
            all.update({entity.get_full_id():entity})   # call for self
    higher_level = hierarchy[index - 1]                 # one up;)
    if all:
        if higher_level == 'C':
            holder = ResidueHolder(name, all)
        elif higher_level == 'R':
            holder = AtomHolder(name, all)
        elif higher_level == 'M':
            holder = ChainHolder(name, all)
        else:
            holder = Holder(higher_level, all)
    else:
        raise ValueError, "einput got no input entites."
    holder.set_sort_tuple()
    return holder

def get_children(entity, level):
    """ return unique entities of lower or equal level
    """
    entity.set_table()
    return entity.table[level]

def get_parent(entity, level):
    """ return unique entities of higher level
    """
    parent = entity.get_parent(level)   # get the correct parent
    return {parent.get_full_id(): parent}
